package fr.miage.resources;

import java.io.IOException;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import fr.miage.dao.AddressDAO;
import fr.miage.model.Address;

@Path("/address")
public class AddressResource {
	
	private AddressDAO addressDAO = new AddressDAO();
	private Logger logger = Logger.getRootLogger();
	
	@GET
	@Path("/{id:[0-9]+}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAddress(@PathParam(value="id")String idAddress){
		Address address = addressDAO.getById(idAddress);
		ObjectMapper mapper = new ObjectMapper();
		if(address == null){
			return Response.status(404).build();
		}else{
			String fluxJson;
			try {
				fluxJson = mapper.writeValueAsString(address);
				return Response.ok(fluxJson).build();
			} catch (JsonGenerationException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (JsonMappingException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (IOException e) {
				logger.error(e);
				return Response.status(500).build();
			}
		}
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAddressByUser(@QueryParam(value="idUser")String idUser){
		Address address = addressDAO.getAddressByUser(idUser);
		ObjectMapper mapper = new ObjectMapper();
		if(address == null){
			return Response.status(404).build();
		}else{
			String fluxJson;
			try {
				fluxJson = mapper.writeValueAsString(address);
				return Response.ok(fluxJson).build();
			} catch (JsonGenerationException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (JsonMappingException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (IOException e) {
				logger.error(e);
				return Response.status(500).build();
			}
		}
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response addAddress(Address address){
		if (address == null) {
			return Response.status(400).entity("User n'est pas correctement formé").build();
		}else{
			int nbRes = addressDAO.addAddress(address);
			if(nbRes == -1){
				return Response.status(409).entity("Cette adresse existe déjà").build();
			}else if(nbRes != 1){
				return Response.status(400).entity("Problème lors de l'insertion en base de données, données incorrectes").build();
			}else{
				return Response.ok().build();
			}
		}
	}
}
